<template>
	<view class="duty-swiper-container">
		<!-- 顶部切换栏 -->
		<view class="tab-header">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: activeIndex === index }"
				@click="switchTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 滑动容器 -->
		<swiper class="swiper-container" :current="activeIndex" @change="handleSwiperChange" :duration="300">
			<swiper-item v-for="(tab, index) in tabs" :key="index">
				<transition name="fade" mode="out-in">
					<view v-show="activeIndex === index" class="swiper-content">
						<keep-alive>
							<duty-driver-view v-if="index === 0 && shouldRender(index)" />
							<duty-view v-if="index === 1 && shouldRender(index)" />
						</keep-alive>
					</view>
				</transition>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import DutyDriverView from './duty-driver.vue';
	import DutyView from './duty.vue';

	export default {
		components: {
			DutyDriverView,
			DutyView
		},
		data() {
			return {
				tabs: ['司机值班', '节假日值班'],
				activeIndex: 0,
				loadedPages: [false, false]
			};
		},
		mounted() {
			// 预加载第一页数据
			this.preloadData(this.activeIndex);
		},
		methods: {
			// 切换 Tab
			switchTab(index) {
				this.activeIndex = index;
				this.preloadData(index);
			},

			// 监听滑动事件
			handleSwiperChange(e) {
				const index = e.detail.current;
				this.activeIndex = index;
				this.preloadData(index);
			},

			// 预加载数据
			preloadData(index) {
				// 如果已经加载过就不再重复加载
				if (this.loadedPages[index]) return;

				// 模拟加载数据（根据实际组件方法调用）
				// 注意：在小程序中无法通过 $refs 获取组件实例的方法，建议使用事件或全局状态管理
				// 这里只是示意，实际可以结合 store 或全局变量处理
				this.loadedPages[index] = true;
			},

			// 控制组件是否渲染
			shouldRender(index) {
				return this.loadedPages[index] || index === this.activeIndex;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.duty-swiper-container {
		padding: 20rpx;
		height: 100vh; // 全屏高度
		display: flex;
		flex-direction: column;
		overflow: visible;
	}

	.tab-header {
		display: flex;
		justify-content: center;
		margin-bottom: 30rpx;
		background-color: #f0f0f0;
		border-radius: 80rpx;
		overflow: hidden;
		width: 60%;
		margin-left: 20%;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		color: #666;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		z-index: 1;
		position: relative;
		transition: all 0.3s ease;
	}

	.tab-item.active {
		background-color: #007AFF;
		color: #fff;
	}

	.swiper-container {
		flex: 1;
		/* 关键：占据剩余空间 */
		height: calc(100vh - 120rpx);
		/* 减去顶部导航和padding */
	}

	.swiper-content {
		height: 100%;
		/* 继承父容器高度 */
	}

	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.3s ease;
	}

	.fade-enter-from,
	.fade-leave-to {
		opacity: 0;
	}
</style>